package com.imooc.order.message;

import cn.hutool.json.JSONUtil;
import com.imooc.product.common.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class ProductInfoReceiver {

    private static final String PRODUCT_STOCK_TEMPLATE = "product_stock_%s";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queuesToDeclare = @Queue("productInfo"))
    public void process(String message){

        // message => ProductInfoOutput
       // ProductInfoOutput output = JSONUtil.parseObj(message).toBean(List<ProductInfoOutput>);
        List<ProductInfoOutput> productInfoOutputs = JSONUtil.parseArray(message).toList(ProductInfoOutput.class);
        log.info("从队列[{}]接收到消息: {}","productInfo",productInfoOutputs);
        // 储存到redis中

        productInfoOutputs.forEach(output->{
            stringRedisTemplate.opsForValue().set(String.format(PRODUCT_STOCK_TEMPLATE,output.getProductId()),
                    String.valueOf(output.getProductStock()));
        });

    }
}
